<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2018/12/24
 * Time: 17:16
 */
namespace common\logics\publishtask;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;
use yii\db\Exception;

class PublishTaskLogic extends BaseObject implements IPublishTask
{

    /** @var \common\sources\read\buyuser\BuyUserAccess $RBuyUserAccess **/
    private $RBuyUserAccess;
    /** @var \common\sources\write\buyuser\BuyUserAccess $WBuyUserAccess **/
    private $WBuyUserAccess;

    /** @var \common\sources\read\shop\ShopAccess $RShopAccess **/
    private $RShopAccess;
    /** @var \common\sources\read\businessacount\BusinessAcountAccess $RBusinessAcountAccess **/
    private $RBusinessAcountAccess;
    /** @var \common\sources\write\businessacount\BusinessAcountAccess $WBusinessAcountAccess **/
    private $WBusinessAcountAccess;
    /** @var \common\sources\read\taskcommod\TaskCommodAccess $RTaskCommodAccess ***/
    private $RTaskCommodAccess;
    /** @var \common\sources\write\taskcommod\TaskCommodAccess $WTaskCommodAccess **/
    private $WTaskCommodAccess;
    /** @var \common\sources\write\businesspepperrecord\BusinessPepperRecordAccess $WBusinessPepperRecordAccess ***/
    private $WBusinessPepperRecordAccess;
    /** @var \common\sources\write\businessdepositrecord\BusinessDepositRecordAccess $WBusinessDepositRecordAccess ***/
    private $WBusinessDepositRecordAccess;
    /** @var \common\sources\write\taskcommodlog\TaskCommodLogAccess $WTaskCommodLogAccess ***/
    private $WTaskCommodLogAccess;
    /** @var \common\sources\read\taskcommodkeywords\TaskCommodKeywordAccess $RTaskCommodKeywordAccess  **/
    private $RTaskCommodKeywordAccess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess $RTaskOrderAccess ***/
    private $RTaskOrderAccess;
    /** @var \common\sources\read\valueservice\ValueServiceAccess $RValueServiceAccess ***/
    private $RValueServiceAccess;
    /*** @var \common\sources\read\taskshopimage\TaskShopImageAccess $RTaskShopImageAccess **/
    private $RTaskShopImageAccess;
    /** @var \common\sources\read\praisekeywords\PraiseKeywordsAccess $RPraiseKeywordsAccess **/
    private $RPraiseKeywordsAccess;
    /** @var \common\sources\read\valueserviceprohibit\ValueServiceProhibitAccess $RValueServiceProhibitAccess ***/
    private $RValueServiceProhibitAccess;

    public function init()
    {
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->WBuyUserAccess = Yii::$container->get("WBuyUserAccess");
        $this->RShopAccess = Yii::$container->get("RShopAccess");
        $this->RBusinessAcountAccess = Yii::$container->get('RBusinessAcountAccess');
        $this->WBusinessAcountAccess = Yii::$container->get("WBusinessAcountAccess");
        $this->WBusinessPepperRecordAccess = Yii::$container->get("WBusinessPepperRecordAccess");
        $this->WBusinessDepositRecordAccess = Yii::$container->get("WBusinessDepositRecordAccess");
        $this->RTaskCommodAccess = Yii::$container->get("RTaskCommodAccess");
        $this->WTaskCommodAccess = Yii::$container->get("WTaskCommodAccess");
        $this->WTaskCommodLogAccess = Yii::$container->get("WTaskCommodLogAccess");
        $this->RTaskCommodKeywordAccess = Yii::$container->get("RTaskCommodKeywordAccess");
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->RValueServiceAccess = Yii::$container->get("RValueServiceAccess");
        $this->RTaskShopImageAccess = Yii::$container->get("RTaskShopImageAccess");
        $this->RValueServiceProhibitAccess = Yii::$container->get("RValueServiceProhibitAccess");
        $this->RPraiseKeywordsAccess = Yii::$container->get("RPraiseKeywordsAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    //获取绑定店铺
    public function getBandShop($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['plat_type'])){
            return Tool::returnJson([],402,"平台类型不能为空");
        }
        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($buyer)){
            return Tool::returnJson([],403,"该商家不存在");
        }
        $data['shop_type'] = $data['plat_type'];
        $shops = $this->RShopAccess->getBusinessShop($data);
        return Tool::returnJson($shops,200,"成功");
    }
    //发布任务操作
    public function addPublishTask($data)
    {
        if(empty($data['bus_id'])){
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['pay_task_amount'])){
            return Tool::returnJson([],402,"支付任务金额不能为空");
        }
        if(empty($data['pay_task_commisse'])){
            return Tool::returnJson([],403,"支付任务佣金不能为空");
        }
        if(empty($data['task_commod_id'])){
            return Tool::returnJson([],405,"任务订单id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],406,"安全码不能为空");
        }
        if(md5($data['bus_id'].$data['task_commod_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],407,"安全码不正确");
        }
        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($buyer)){
            return Tool::returnJson([],408,"该商家不存在");
        }
        if($buyer['role'] != 2){
            return Tool::returnJson([],409,"商家角色不正确");
        }
        //查商家账号中心数据
        $businessAcount = $this->RBusinessAcountAccess->getAcount($data['bus_id']);
        if(empty($businessAcount))
        {
            return Tool::returnJson([],410,"您的账号没有充值,请先充值");
        }
        if($data['pay_task_amount'] > $businessAcount['ava_deposit'])
        {
            return Tool::returnJson([],411,"您的押金不足，请先充值");
        }
        if(number_format($data['pay_task_commisse'],2,'.','') > number_format($businessAcount['ava_pepper'],2,'.',''))
        {
            return Tool::returnJson([],412,"您的可用花椒不足");
        }
        //查看任务是否存在
        $task_commod = $this->RTaskCommodAccess->getTaskCommodById($data['task_commod_id']);
        if(empty($task_commod)){
            return Tool::returnJson([],413,"该任务不存在");
        }
        if($task_commod['pay_task_commisse'] != $data['pay_task_commisse'])
        {
            return Tool::returnJson([],415,"任务佣金不正确");
        }
        if($task_commod['pay_task_amount'] != $data['pay_task_amount'])
        {
            return Tool::returnJson([],416,"商品押金不正确");
        }
        if(!($task_commod['public_task_status'] == 4 && $task_commod['task_status'] == 1))
        {
            return Tool::returnJson([],417,"该任务不能支付");
        }
        //返回结构
        $task_types = Yii::$app->params['plat_task_type'][$task_commod['plat_type']];
        foreach ($task_types as &$task_ty)
        {
            if($task_ty['task_type'] == $task_commod['task_type'])
            {
                $task_commod['task_type_name'] = $task_ty['name'];
            }
        }
        //修改账号佣金
        $ava_deposit = number_format($businessAcount['ava_deposit'] - $data['pay_task_amount'],2,'.','');               //可用押金
        $freezing_deposit = number_format($businessAcount['freezing_deposit'] + $data['pay_task_amount'],2,'.','');     //冻结押金
        $ava_pepper = number_format($businessAcount['ava_pepper'] - $data['pay_task_commisse'],2,'.','');               //可用花椒
        $freezing_golds = number_format($businessAcount['freezing_golds'] + $data['pay_task_commisse'],2,'.','');       //冻结花椒
        $arr = [
            "ava_deposit" => $ava_deposit,
            'freezing_deposit' => $freezing_deposit,
            "ava_pepper" => $ava_pepper,
            "freezing_golds" => $freezing_golds,
            'bus_id' => $data['bus_id'],
        ];
        $transaction = Yii::$app->db->beginTransaction();
        try{
            //修改任务订单状态
            $pArr = [
                'public_task_status' => 5,
                'task_status' => 2,
                'id' => $data['task_commod_id'],
            ];
            $taskStatus = $this->WTaskCommodAccess->payTaskCommod($pArr);
            if($taskStatus){
                //修改账号中心
                $this->WBusinessAcountAccess->modifyAcount($arr);
                //消耗押金记录
                $deposits_arr =[
                    "bus_id" => $data['bus_id'],
                    'task_commod_id' => $data['task_commod_id'],
                    "task_id" => $task_commod['task_id'],
                    'expend' => $data['pay_task_amount'],
                    'income' => 0,
                    'type' => 2,
                    "balance" => $ava_deposit,
                    "freeze_change" => number_format($data['pay_task_amount'],2,".",""),
                    "freeze_balance" => $freezing_deposit,
                    "remark" => '发布任务扣除押金',
                    "operatorId" => $buyer['phone'],
                ];
                $this->WBusinessDepositRecordAccess->addDepositRecord($deposits_arr);
                //消耗花椒记录
                $pepper_arr = [
                    "bus_id" => $data['bus_id'],
                    "task_id" => $task_commod['task_id'],
                    'task_commod_id' => $data['task_commod_id'],
                    'expend' => $data['pay_task_commisse'],
                    'income' => 0,
                    'type' => 2,
                    "balance" => $ava_pepper,
                    "freeze_change" => number_format($data['pay_task_commisse'],2,".",""),
                    "freeze_balance" => $freezing_golds,
                    "remark" => '发布任务扣除花椒',
                    "operatorId" => $buyer['phone'],
                ];
                $this->WBusinessPepperRecordAccess->addPeppersRecord($pepper_arr);
                //添加操作日志记录
                $this->WTaskCommodLogAccess->addTaskCommodLog(['bus_id'=>$data['bus_id'],'task_status'=>2,"status_remark"=>'任务已经支付',"remark" => '已支付',"operator"=>$buyer['phone'],'task_id'=> $data['task_commod_id']]);
                //修改最后发布任务时间
                $this->WBuyUserAccess->modifySendRecieveTime(['id'=> $data['bus_id']]);
                $transaction->commit();
                return Tool::returnJson([],200,"支付成功，任务已发布等待客服审核");
            }
            $transaction->rollBack();
            return Tool::returnJson([],418,"发布任务失败");
        }catch(\Exception $e){
            $transaction->rollBack();
            return Tool::returnJson([],5000,"发布任务异常".$e->getMessage());
        }

    }
    //撤销任务
    public function taskRevocate($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家id不能为空");
        }
        if(empty($data['task_commod_id']))
        {
            return Tool::returnJson([],402,"主任务id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if(md5($data['bus_id'].$data['task_commod_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        $task_commod = $this->RTaskCommodAccess->getTaskCommodById($data['task_commod_id']);
        if(empty($task_commod))
        {
            return Tool::returnJson([],406,"该任务不存在");
        }
        if($task_commod['task_status'] >4)
        {
            return Tool::returnJson([],407,"该任务结束不能撤销");
        }
        if($task_commod['surplus_task_num'] == 0)
        {
            return Tool::returnJson([],408,"无可接任务不能撤销");
        }
        //账号基础信息
        $business = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($business))
        {
            return Tool::returnJson([],409,"该任务不能撤销");
        }
        //回退账号余额
        $business_account = $this->RBusinessAcountAccess->getAcount($data['bus_id']);
        if(empty($business_account))
        {
            return Tool::returnJson([],410,"商家账号信息异常");
        }
        $transaction = Yii::$app->db->beginTransaction();
        try{

            $res = $this->WTaskCommodAccess->modifyTaskStatus(['task_status' =>5,'task_commod_id'=>$data['task_commod_id']]);
            if($res)
            {
                if($task_commod['task_status'] == 2)
                {
                    $pay_task_amount = $task_commod['pay_task_amount'];                 //任务押金金额
                    $pay_task_commisse = $task_commod['pay_task_commisse'];              //任务佣金
                    $ava_deposit = number_format($business_account['ava_deposit']+ $pay_task_amount,2,".","");
                    $ava_pepper = number_format($business_account['ava_pepper'] + $pay_task_commisse,2,".","");
                    $freezing_deposit = number_format($business_account['freezing_deposit'] - $pay_task_amount,2,".","");
                    $freezing_golds = number_format($business_account['freezing_golds'] - $pay_task_commisse,2,".","");
                    //修改账号余额
                    $accout_arr = [
                        "ava_deposit" => $ava_deposit,
                        "ava_pepper" => $ava_pepper,
                        "freezing_deposit" => $freezing_deposit,
                        "freezing_golds" => $freezing_golds,
                        'bus_id' => $data['bus_id'],
                    ];
                    $account_res =$this->WBusinessAcountAccess->modifyAcount($accout_arr);
                    if(!$account_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],411,"取消任务返还商家押金和花椒失败");
                    }
                    //退押金记录
                    $deposit_arr = [
                        "bus_id" => $data['bus_id'],
                        "task_commod_id" => $data['task_commod_id'],
                        "task_id" => $task_commod['task_id'],
                        "expend" => 0,
                        "type" => 3,
                        "income" => $pay_task_amount,
                        "balance" => $ava_deposit,
                        "freeze_change" => -$pay_task_amount,
                        "freeze_balance" =>$freezing_deposit,
                        "remark" => "撤销任务退还押金",
                        "operatorId" => $business['phone'],
                    ];
                    $deposite_res = $this->WBusinessDepositRecordAccess->addDepositRecord($deposit_arr);
                    if(!$deposite_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],412,"撤销任务退还押金失败");
                    }
                    //退花椒
                    $pepper_arr = [
                        "bus_id" => $data['bus_id'],
                        "task_commod_id" => $data['task_commod_id'],
                        "task_id" => $task_commod['task_id'],
                        "expend" => 0,
                        "type" => 3,
                        "income" => $pay_task_commisse,
                        "balance" => $ava_pepper,
                        "freeze_change" => -$pay_task_commisse,
                        "freeze_balance" => $freezing_golds,
                        "remark" =>"撤销任务退还花椒",
                        "operatorId" => $business['phone']
                    ];
                    $pepper_res = $this->WBusinessPepperRecordAccess->addPeppersRecord($pepper_arr);
                    if(!$pepper_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],413,"撤销任务退还花椒失败");
                    }

                }else if($task_commod['task_status'] == 4)
                {
                    $refund_pay_task_amount = number_format($task_commod['price'] * $task_commod['num']* 1.05 * $task_commod['surplus_task_num'] + $task_commod['freight_deposit'] * $task_commod['surplus_task_num'],2,".","");   //剩余任务押金 任务押金金额
                    $value_service = $this->RValueServiceAccess->getValueServiceByCommodId($task_commod['id']);
                    $refund_service_commisse = number_format($value_service['return_type_pepper']*$task_commod['surplus_task_num'] + $value_service['chat_pepper']* $task_commod['surplus_task_num']+ $value_service['extend_pepper'] * $task_commod['surplus_task_num']
                        + $value_service['sex_pepper'] * $task_commod['surplus_task_num'] + $value_service['praise_pepper']* $task_commod['surplus_task_num'] + $value_service['buy_age_pepper'] * $task_commod['surplus_task_num']+
                    $value_service['reword_commise']* $task_commod['surplus_task_num'] + $value_service['service_pepper'] * $task_commod['surplus_task_num'] + $task_commod['item_commisse']* $task_commod['surplus_task_num']
                        + $task_commod['img_prase_type_pepper']*$task_commod['surplus_task_num'],2,".","") ;
                    //退还佣金和本金
                    //退还本金
                    //退押金记录
                    $deposit_arr = [
                        "bus_id" => $data['bus_id'],
                        "task_commod_id" => $data['task_commod_id'],
                        "task_id" => $task_commod['task_id'],
                        "expend" => 0,
                        "type" => 3,
                        "income" => $refund_pay_task_amount,
                        "balance" => number_format($business_account['ava_deposit'] + $refund_pay_task_amount,2,".",""),
                        "freeze_change" => -$refund_pay_task_amount,
                        "freeze_balance" => number_format($business_account['freezing_deposit'] - $refund_pay_task_amount,2,".",""),
                        "remark" => "商家撤销任务退还押金",
                        "operatorId" => $business['phone'],
                    ];
                    $deposite_res = $this->WBusinessDepositRecordAccess->addDepositRecord($deposit_arr);
                    if(!$deposite_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],415,"商家撤销任务退还押金失败");
                    }
                    //退还佣金
                    $pepper_arr = [
                        "bus_id" => $data['bus_id'],
                        "task_commod_id" => $data['task_commod_id'],
                        "task_id" => $task_commod['task_id'],
                        "expend" => 0,
                        "type" => 3,
                        "income" => $refund_service_commisse,
                        "balance" => number_format($business_account['ava_pepper'] + $refund_service_commisse,2,".",""),
                        "freeze_change" => -$refund_service_commisse,
                        "freeze_balance" => number_format($business_account['freezing_golds'] - $refund_service_commisse,2,".",""),
                        "remark" =>"商家撤销任务退还花椒",
                        "operatorId" => $business['phone']
                    ];
                    $pepper_res = $this->WBusinessPepperRecordAccess->addPeppersRecord($pepper_arr);
                    if(!$pepper_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],416,"商家撤销任务退还花椒失败");
                    }
                    //修改商家账号
                    $ava_deposit = number_format($business_account['ava_deposit']+ $refund_pay_task_amount,2,".","");
                    $ava_pepper = number_format($business_account['ava_pepper'] + $refund_service_commisse,2,".","");
                    $freezing_deposit = number_format($business_account['freezing_deposit'] - $refund_pay_task_amount,2,".","");
                    $freezing_golds = number_format($business_account['freezing_golds'] - $refund_service_commisse,2,".","");
                    //修改账号余额
                    $accout_arr = [
                        "ava_deposit" => $ava_deposit,
                        "ava_pepper" => $ava_pepper,
                        "freezing_deposit" => $freezing_deposit,
                        "freezing_golds" => $freezing_golds,
                        'bus_id' => $data['bus_id'],
                    ];
                   $bus_res = $this->WBusinessAcountAccess->modifyAcount($accout_arr);
                   if(!$bus_res)
                   {
                       $transaction->rollBack();
                       return Tool::returnJson([],417,"商家账号修改失败");
                   }
                }
                //添加操作日志记录
                $this->WTaskCommodLogAccess->addTaskCommodLog(['bus_id'=>$data['bus_id'],'task_status'=>5,"status_remark"=>'任务已经取消',"remark" => '',"operator"=>$business['phone'],'task_id'=> $data['task_commod_id']]);
                $transaction->commit();
                return Tool::returnJson([],200,"撤销任务成功");
            }
            $transaction->rollBack();
            return Tool::returnJson([],410,"撤销失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"撤销异常".$e->getMessage());
        }
    }
}